package utils.sshutils;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;


public class SshUtil {
    private static String DEFAULT_CHAR_SET = "UTF-8";
    private static String tipStr = "=======================%s=======================";
    private static String splitStr = "=====================================================";

    /**
     * 登录主机
     * @return
     *      登录成功返回true，否则返回false
     */
    public static Connection login(String ip, String userName, String password){
        boolean isAuthenticated = false;
        Connection conn = null;
        long startTime = Calendar.getInstance().getTimeInMillis();
        try {
            conn = new Connection(ip);
            conn.connect(); // 连接主机
			// 认证
            isAuthenticated = conn.authenticateWithPassword(userName, password);
            if(isAuthenticated){
                System.out.println(String.format(tipStr, "认证成功"));
            } else {
                System.out.println(String.format(tipStr, "认证失败"));
            }
        } catch (IOException e) {
            System.err.println(String.format(tipStr, "登录失败"));
            e.printStackTrace();
        }
        long endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("登录用时: " + (endTime - startTime)/1000.0 + "s\n" + splitStr);
        return conn;
    }
 
    /**
     * 远程执行shell脚本或者命令
     * @param cmd
     *      即将执行的命令
     * @return
     *      命令执行完后返回的结果值
     */
    public static String execute(Connection conn, String cmd){
        String result = "";
        Session session = null;
        try {
            if(conn != null){
				// 打开一个会话
                session = conn.openSession();
				// 执行命令
                session.execCommand(cmd);
                result = processStdout(session.getStdout(), DEFAULT_CHAR_SET);

                //如果为得到标准输出为空，说明脚本执行出错了
                if(StringUtils.isBlank(result)){
                    System.err.println("【得到标准输出为空(脚本执行出错)】\n执行的命令如下：\n" + cmd);
                    result = processStdout(session.getStderr(), DEFAULT_CHAR_SET);
                }else{
                    System.out.println("【执行命令成功】\n执行的命令如下：\n" + cmd);
                }
            }
        } catch (IOException e) {
            System.err.println("【执行命令失败】\n执行的命令如下：\n" + cmd + "\n" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.close();
            }
            if (session != null) {
                session.close();
            }
        }
        return result;
    }

    /**
     * 解析脚本执行返回的结果集
     * @param in 输入流对象
     * @param charset 编码
     * @return
     *       以纯文本的格式返回
     */
    private static String processStdout(InputStream in, String charset){
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line;
            while((line = br.readLine()) != null){
                buffer.append(line).append("\n");
            }
        } catch (IOException e) {
            System.err.println("解析脚本出错：" + e.getMessage());
            e.printStackTrace();
        }
		return buffer.toString();
    }


    public static void initApp(String ip,String userName,String password){
        Connection conn =  SshUtil.login(ip, userName, password);
        String cmd = "ls"
                +"&&chmod -R 777 /home/app/"
                +"&&mv /home/app/nginx /root/"
                +"&&chmod -R 777 /root/nginx/"
                +"&&cd /root/nginx/sbin" +
                "&&./nginx"
                +"&&cd /home/app/redis/" +
                "&&./redis-server redis.conf";
        SshUtil.execute(conn, cmd);
    }
    public static void startJar(String ip, String userName, String password, Map<String,String> config){
        Connection conn =  SshUtil.login(ip, userName, password);
        StringBuilder configStr = new StringBuilder();

        for (Map.Entry<String, String> entry : config.entrySet()) {
            configStr.append(" --").append(entry.getKey()).append("=").append(entry.getValue());
        }
        //String configStr = "--spring.redis.host=101.35.141.200 " +
        //                 "--spring.redis.password=zzz5567786";
        String cmd = "ls"
                +"&&cd /home/app"
                +"&&nohup /home/app/jdk1.8.0_144/bin/java -jar app.jar" + configStr + " > /dev/null 2>&1 &";

        SshUtil.execute(conn, cmd);
    }

    public static void stopJar(String ip,String userName,String password){
        Connection conn =  SshUtil.login(ip, userName, password);
        String getPid = "netstat -lnp|grep 8080";
        String execute = SshUtil.execute(conn, getPid);
        String[] s = execute.split(" ");
        String pid = "";
        for (int i = 0; i < s.length; i++) {
            if (s[i].contains("/java")) {
                pid = s[i].substring(0, s[i].indexOf("/java"));
                break;
            }
        }
        if (StringUtils.isNotBlank(pid)) {
            Connection conn1 =  SshUtil.login(ip, userName, password);
            String stopCmd = "kill -9 " + pid;
            SshUtil.execute(conn1,stopCmd);
        }
    }

    public static void main(String[] args){
        String ip = "192.168.1.196";
        String userName = "root";
        String password = "3h1admin";
        //SshUtil.stopJar(ip, userName, password);
        Map<String,String> map = new HashMap<>();
        map.put("spring.redis.host","101.35.141.200");
        map.put("spring.redis.password","zzz5567786");
        SshUtil.startJar(ip, userName, password,map);

        //Connection conn =  SshUtil.login(ip, userName, password);
      /*  String config = "--spring.redis.host=101.35.141.200 " +
                         "--spring.redis.password=zzz5567786";
        String cmd = "ls"
                //+"&&chmod -R 777 /home/app/"
                //+"&&mv /home/app/nginx /root/"
                //+"&&chmod -R 777 /root/nginx/"
                //+"&&cd /root/nginx/sbin" +
                //"&&./nginx"
                //+"&&cd /home/app/redis/" +
                //"&&./redis-server redis.conf"
                +"&&cd /home/app"
                +"nohup /home/app/jdk1.8.0_144/bin/java -jar app.jar " + config + " > /dev/null 2>&1 &";
        String cmd1 = "netstat -lnp|grep 8080";
        String result = SshUtil.execute(conn, cmd1);
        System.out.println(splitStr + "\n执行的结果如下: \n" + result + splitStr);*/
    }
}
